package com.monika.main.system.servcie;

import cn.hutool.core.date.DateUtil;
import com.monika.main.system.constant.CacheConstant;
import com.monika.main.system.constant.Constant;
import com.monika.main.system.domain.entity.LoginUser;
import com.monika.main.system.domain.entity.SysUser;
import com.monika.main.system.exception.BlackListException;
import com.monika.main.system.exception.UserPasswordRetryExceedException;
import com.monika.main.system.factory.AsyncFactory;
import com.monika.main.system.factory.AsyncManager;
import com.monika.main.system.util.IpUtil;
import com.monika.main.system.util.RedisCache;
import com.monika.main.system.util.StringUtil;
import com.monika.main.system.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Author whh
 * Date 2023/04/17/ 21:06
 * <p></p>
 */
@Component
public class SysLoginService {

//    @Resource
    private AuthenticationManager authenticationManager;


    @Autowired
    private ISysConfigService configService;


    @Autowired
    private ISysUserService sysUserService;
    /**
     * 密码重试次数
     */
    @Value("${primal.security.pwdretrycnt}")
    private int pwdretrycnt;

    @Value("${primal.security.lockTime}")
    private int lockTime;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public void login(String username, String password)  {
        // IP黑名单校验
        blackIpValidate();


        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {

            if (e instanceof BadCredentialsException) {
                Integer retryCount = RedisCache.get(CacheConstant.PWD_ERR_CNT_KEY + username);
                if (Objects.isNull(retryCount)) {
                    retryCount = 1;
                }
                if (retryCount >= pwdretrycnt) {
                    throw new UserPasswordRetryExceedException("user password retry exceed limit", retryCount, lockTime);
                }
                retryCount = retryCount + 1;

                RedisCache.put(CacheConstant.PWD_ERR_CNT_KEY + username, retryCount, lockTime, TimeUnit.MINUTES);
                AsyncManager.me().execute(AsyncFactory.recordSysUserLoginLog(username, Constant.LOGIN_FAIL, "user password retry " + retryCount));
                throw e;

            } else {
                AsyncManager.me().execute(AsyncFactory.recordSysUserLoginLog(username, Constant.LOGIN_FAIL, StringUtil.substring(e.getMessage(), 0, 2000)));
                throw e;
            }
        }

        AsyncManager.me().execute(AsyncFactory.recordSysUserLoginLog(username, Constant.LOGIN_SUCCESS, "user.login.success"));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        recordLoginInfo(loginUser.getUserId());
    }


    /**
     * IP黑名单处理
     */
    private void blackIpValidate(){
        // IP黑名单校验
        String blackStr = configService.querySysConfigValueCache("sys.login.blackIPList");
        String ipAddr = IpUtil.getIpAddr();
        if (IpUtil.isMatchedIp(blackStr, ipAddr))
        {
            throw new BlackListException("ip "+ipAddr+" is illegal");
        }
    }


    private void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUser_id(userId);
        sysUser.setLogin_ip(IpUtil.getIpAddr());
        sysUser.setLogin_date(DateUtil.now());
        sysUserService.updateUserProfile(sysUser);
    }
}
